package com.waijiaojun.tpo.service;

import com.waijiaojun.tpo.utils.AliyunOssUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.waijiaojun.tpo.entity.Category;
import com.waijiaojun.tpo.repository.CategoryDao;

@Service
public class CategoryService{

    @Resource
    private CategoryDao categoryDao;

    public int insert(Category pojo){
        return categoryDao.insert(pojo);
    }

    public int insertSelective(Category pojo){
        return categoryDao.insertSelective(pojo);
    }

    public int insertList(List<Category> pojos){
        return categoryDao.insertList(pojos);
    }

    public int update(Category pojo){
        return categoryDao.update(pojo);
    }

    public List<Category> findAll() {
        return categoryDao.getAll();
    }

    public Category save(Category category) {
        if(category.getId()==null) {
            categoryDao.insertSelective(category);
        }else{
            categoryDao.update(category);
        }

        // 保存文件到OSS，并更新url
        String videoUrl=null;
        String coverUrl=null;
        if(category.getVideoFile()!=null && !category.getVideoFile().isEmpty()) {
            videoUrl = AliyunOssUtil.uploadCategoryFile(category.getVideoFile(), category.getId());
        }
        if(category.getCoverFile()!=null && !category.getCoverFile().isEmpty()) {
            coverUrl = AliyunOssUtil.uploadCategoryFile(category.getCoverFile(), category.getId());
        }

        if(videoUrl!=null || coverUrl!=null){
            if(videoUrl!=null){
                category.setVideo_url(videoUrl);
            }
            if(coverUrl!=null){
                category.setCover_url(coverUrl);
            }
            categoryDao.update(category);
        }

        return category;
    }

    public Category findById(Long id) {
        return categoryDao.findById(id);
    }
}
